<template>
	<div class="rc-container">
		<div class="tag-group">
			<div class="tag-label">片区类型</div>
			<div class="tag-cell">
				<div class="tag-item" v-for="(item, index) in typeList" :key="index"
					:class="{ active: typeCurrent.includes(index) }" @click="typeClick(index)">
					{{ item.label }}
				</div>
			</div>
		</div>
		<div class="tag-group">
			<div class="tag-label">生效类型</div>
			<div class="tag-cell">
				<div class="tag-item" v-for="(item, index) in stateTypeList" :key="index"
					:class="{ active: stateCurrent.includes(index) }" @click="stateClick(index)">
					{{ item.label }}
				</div>
			</div>
		</div>
		<!-- 搜索 -->
		<div class="search">
			<div class="search-input"><el-input v-model="queryForm.areaName" placeholder="搜索片区名称" :prefix-icon="Search"
					@keyup.enter.native="getList" /></div>
			<div class="export" @click="open">
				<span>+添加区域</span>
			</div>
		</div>
		<!-- 表格 -->
		<div class="table-grop" v-loading="tableLoading" v-if="tableData && tableData.length">
			<div class="table-cell" v-for="(item, index) in tableData" :key="index">
				<div class="header">
					<div class="name">{{ item.areaName }}</div>
					<div class="tip" :class="{ blue: !item.status }">{{
            item.status ? '未生效，请配置区域边界！' : '已生效'
          }}</div>
				</div>
				<div class="con">
					<div class="con-text"><span
							style="color: rgba(255, 255, 255, 0.6)">景区/商圈：</span>{{ item.distinction }}
					</div>
					<div class="con-right">
						<div class="edit" @click="editArea(item, index)">配置</div>
						<div class="line"></div>
						<div class="del" @click="delArea(item.id)">删除</div>
					</div>
				</div>
				<div class="select">
					<!-- <div class="bor">
            {{item.nodeId}}
            {{ item ? areaList[item.nodeId].label : '' }}
          </div> -->
					<!-- <div class="bor">
            <el-tree-select
              v-model="item.area"
              :data="areaSelectData"
              :render-after-expand="false"
            />
          </div> -->
				</div>
			</div>
		</div>
		<div class="not-data" v-else>暂无数据</div>
		<!-- 弹窗 -->
		<div class="statistics-dio" :class="{ show: sdShow }">
			<div class="head">
				<div class="back" @click="back">
					<div style="margin-top: 3px"><el-icon>
							<ArrowLeft />
						</el-icon></div>
					<div>返回</div>
				</div>
				添加/编辑区域
				<div class="save" @click="savePath">保存</div>
			</div>
			<div class="title"> 基本信息 </div>
			<div class="or-group">
				<div class="label">区域名称</div>
				<div class="val">
					<el-input style="width: 100%" v-model="form.areaName" placeholder="请输入区域名称" />
				</div>
			</div>
			<div class="or-group">
				<div class="label">片区类型</div>
				<div class="val">
					<el-select v-model="form.areaTypeCode" placeholder="请选择" style="width: 100%">
						<el-option v-for="(item, index) in typeList" :key="index" :label="item.label"
							:value="item.value" />
					</el-select>
				</div>
			</div>
			<div class="or-group">
				<div class="label">生效类型</div>
				<div class="val">
					<el-select v-model="form.status" placeholder="请选择" style="width: 100%">
						<el-option v-for="(item, index) in stateTypeList" :key="index" :label="item.label"
							:value="item.value" />
					</el-select>
				</div>
			</div>

			<div class="title" style="margin-top: 1vw"> 添加信息 </div>
			<!-- <div class="operation-group">
        <div
          class="operation-item"
          v-for="(item, index) in operationList"
          :key="index"
          :class="{ active: operationCurrent == index }"
          @click="operationClick(index)"
        >
          {{ item.label }}
        </div>
      </div> -->
			<!-- 工具栏 -->
			<div class="tools-group">
				<div class="tools-item" :class="{ active: graphicalCurrent === 0 }" @click="CircleDemo(0)">
					<img :src="require('@/assets/images/maps/tuoyuan.png')" alt="" />
					<div>圆形面</div>
				</div>
				<div class="tools-item" :class="{ active: graphicalCurrent == 1 }" @click="CircleDemo(1)">
					<img :src="require('@/assets/images/maps/juxing.png')" alt="" />
					<div>矩形面</div>
				</div>
				<div class="tools-item" :class="{ active: graphicalCurrent == 2 }" @click="CircleDemo(2)">
					<img :src="require('@/assets/images/maps/duobianxing.png')" alt="" />
					<div>多边形面</div>
				</div>
				<div class="tools-item" :class="{ active: graphicalCurrent == 3 }" @click="handedit(3)">
					<img :src="require('@/assets/images/maps/edit.png')" alt="" />
					<div>手动添加</div>
				</div>
			</div>
			<div class="select-cell">
				<div class="select-cell-item">
					<el-select v-model="form.nodeId" placeholder="请选择" style="width: 100%">
						<el-option v-for="(item, index) in areaList" :key="index" :label="item.label"
							:value="item.value" />
					</el-select>
				</div>
				<div class="select-cell-item">
					<el-input v-model="form.distinction" placeholder="输入景区商圈等面数据" />
				</div>
			</div>
			<div class="show-title">查看已添加区域坐标数据<div style="font-size:12px;color:rgba(255,255,255,.6)"
					v-if="operationCurrent === 0 && radius && centerPoint">（圆心坐标：{{ form.circle }}半径：{{ radius }}）</div>
			</div>
			<div class="show-json">
				{{ isEditor ? pathStr : '' }}
			</div>
			<div class="btn-bottom" v-if="isEditor&&graphicalCurrent != 3">
				<el-button type="primary" @click="seePath">查看坐标</el-button>
			</div>
		</div>
	</div>
</template>
<script>
	import {
		defineComponent,
		inject,
		reactive,
		toRefs,
		onMounted,
		nextTick,
		computed,
		onBeforeUnmount,
	} from 'vue';
	import {
		useMapStore
	} from '@/store/modules/map';
	import {
		Search,
		ArrowLeft,
		WarningFilled
	} from '@element-plus/icons-vue';
	import {
		insertArea,
		getSelectByParamsList,
		updateArea,
		deleteAreaById
	} from '@/api/tomae';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	export default defineComponent({
		setup(props, {
			emit
		}) {
			const userStore = useMapStore();
			const state = reactive({
				map: computed(() => userStore.ownMap),
				sdShow: false,
				keywork: '',
				typeList: [
					// {
					//   label: '行政区',
					//   value: 0,
					// },
					// {
					//   label: '重点片区',
					//   value: 1,
					// },
					// {
					//   label: '堵点',
					//   value: 2,
					// },
					// {
					//   label: '堵点',
					//   value: 3,
					// },
					{
						value: 0,
						label: "行政区"
					}, {
						value: 1,
						label: "街道"
					}, {
						value: 2,
						label: "商圈"
					}, {
						value: 3,
						label: "医圈"
					}, {
						value: 4,
						label: "学校"
					}, {
						value: 5,
						label: "景区"
					}
				],
				areaList: [{
						label: '兰山片区',
						value: 0,
					},
					{
						label: '河东片区',
						value: 1,
					},
					{
						label: '罗庄片区',
						value: 2,
					},
					{
						label: '经开片区',
						value: 3,
					},

					{
						label: '北城片区',
						value: 4,
					},
					{
						label: '西部副城片区',
						value: 5,
					},
				],
				stateTypeList: [{
						label: '生效',
						value: 0,
					},
					{
						label: '未生效',
						value: 1,
					},
				],
				stateCurrent: [],
				typeCurrent: [],
				tableData: [],
				areaSelectData: [{
					value: '7789',
					label: '临沂市',
					children: [{
							value: '0',
							label: '兰山区',
						},
						{
							value: '1',
							label: '罗庄区',
						},
						{
							value: '2',
							label: '河东区',
						},
					],
				}, ],
				operationList: [{
						label: '添加区域',
						value: '添加区域',
					},
					{
						label: '扣除区域',
						value: '扣除区域',
					},
					{
						label: '添加道路',
						value: '添加道路',
					},
					{
						label: '扣除道路',
						value: '扣除道路',
					},
				],
				operationCurrent: 0,
				graphicalCurrent: '',
				drawingManager: null,
				form: {
					areaName: '',
					nodeId: '',
					distinction: '',
					areaTypeCode: 0,
					coordinate: '',
					status: 0,
				},
				overlay: null,
				pathObj: {
					polygon: [],
					circular: [],
				},
				pathStr: '',
				queryForm: {
					areaName: '',
					areaTypeCode: '',
					status: '',
				},
				isEditor: false,
				tableLoading: false,
				radius: '',
				centerPoint: '',
			});
			// 片区点击
			const typeClick = (index) => {
				if (state.typeCurrent.includes(index)) {
					state.typeCurrent.splice(state.typeCurrent.indexOf(index), 1);
				} else {
					state.typeCurrent.push(index);
				}
				getList();
			};
			const stateClick = (index) => {
				if (state.stateCurrent.includes(index)) {
					state.stateCurrent.splice(state.stateCurrent.indexOf(index), 1);
				} else {
					state.stateCurrent.push(index);
				}
				getList();
			};
			// 编辑
			const editArea = (item) => {
				back();
				console.log(item);
				state.form = item;
				state.pathStr = item.coordinate;
				state.sdShow = true;
				state.isEditor = true;
				if (item.type === 'polygon') {
					state.graphicalCurrent = 2;
				} else {
					state.radius = item.radius;
					state.centerPoint = new window.BMap.Point(
						state.form.circle.split(',')[0],
						state.form.circle.split(',')[1],
					);
					state.graphicalCurrent = 0;
				}
				drowEditor(item);
			};
			// 添加
			const open = () => {
				back();
				state.sdShow = true;
			};
			// 返回
			const back = () => {
				state.sdShow = false;
				if (state.drawingManager) {
					state.drawingManager.close();
				}
				state.map.clearOverlays();
				state.isEditor = false;
				state.pathObj = {
					polygon: [],
					circular: [],
				};
				state.graphicalCurrent = '';
				state.pathStr = '';
				state.form = {
					areaName: '',
					nodeId: '',
					distinction: '',
					areaTypeCode: 0,
					coordinate: '',
					status: 0,
				};
				state.isEditor = false;
			};
			// 操作点击
			const operationClick = (index) => {
				state.operationCurrent = index;
			};

			const drowEditor = (item) => {
				if (state.map.getZoom() < 16) {
					state.map.setZoom(16);
				}
				if (state.graphicalCurrent === 0) {
					// 绘制圆
					var circle = new window.BMap.Circle(state.centerPoint, state.radius, {
						strokeColor: '#5E87DB',
						fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
						strokeWeight: 3, // 边线宽度，以像素为单位
						strokeOpacity: 1, // 边线透明度，取值范围0-1
						fillOpacity: 0.2, // 填充透明度，取值范围0-1
					});
					state.map.panTo(state.centerPoint);
					state.map.addOverlay(circle);
					state.overlay = circle;
					console.log(state.centerPoint, state.radius);
				} else {
					let arr = [];
					let lng = '';
					item.coordinate.split(',').forEach((item, index) => {
						if (index % 2 === 0) {
							lng = item;
						} else {
							arr.push(new window.BMap.Point(lng, item));
						}
					});
					var polygon = new window.BMap.Polygon(arr, {
						strokeColor: '#5E87DB',
						fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
						strokeWeight: 3, // 边线宽度，以像素为单位
						strokeOpacity: 1, // 边线透明度，取值范围0-1
						fillOpacity: 0.2, // 填充透明度，取值范围0-1
					});
					state.map.panTo(arr[0]);
					state.map.addOverlay(polygon);
					state.overlay = polygon;
				}

				state.overlay.enableEditing();
			};

			// 绘制圆形
			const CircleDemo = (index) => {
				let drawType = [BMAP_DRAWING_CIRCLE, BMAP_DRAWING_RECTANGLE, BMAP_DRAWING_POLYGON][index];
				state.graphicalCurrent = index;
				state.drawingManager = null;
				state.map.clearOverlays();
				state.pathObj = {
					polygon: [],
					circular: [],
				};
				const styleOptions = {
					strokeColor: '#5E87DB', // 边线颜色
					fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
					strokeWeight: 3, // 边线宽度，以像素为单位
					strokeOpacity: 1, // 边线透明度，取值范围0-1
					fillOpacity: 0.2, // 填充透明度，取值范围0-1
					strokeStyle: 'solid', //边线的样式，solid或dashed。
				};
				const labelOptions = {
					borderRadius: '2px',
					background: '#FFFBCC',
					border: '1px solid #E1E1E1',
					color: '#703A04',
					fontSize: '12px',
					letterSpacing: '0',
					padding: '5px',
				};
				// 实例化鼠标绘制工具
				state.drawingManager = new window.BMapLib.DrawingManager(state.map, {
					isOpen: true, // 是否开启绘制模式
					enableCalculate: true, // 绘制是否进行测距测面
					enableSorption: true, // 是否开启边界吸附功能
					sorptiondistance: 20, // 边界吸附距离
					circleOptions: styleOptions, // 圆的样式
					polylineOptions: styleOptions, // 线的样式
					polygonOptions: styleOptions, // 多边形的样式
					rectangleOptions: styleOptions, // 矩形的样式
					labelOptions, // label样式
				});
				state.drawingManager.setDrawingMode(drawType);
				state.drawingManager.open();
				state.drawingManager.addEventListener('overlaycomplete', (e) => {
					state.overlay = e.overlay;
					state.drawingManager.close();
					state.overlay.enableEditing();
					state.isEditor = true;
				});
			};
			// 手动添加
			const handedit = (index) => {
				state.graphicalCurrent = index;
				ElMessageBox.prompt('请输入坐标点', '数据', {
						confirmButtonText: '保存', // 确认按钮改为“保存”
						cancelButtonText: '取消', // 取消按钮改为“取消”
						inputType: 'textarea', // 输入框类型改为 textarea
						inputErrorMessage: '输入内容不能为空', // 错误提示
					})
					.then(({
						value
					}) => {
						if (!value) {
							// 校验内容非空
							ElMessage({
								type: 'error',
								message: '输入内容不能为空',
							});
							return;
						}
						state.pathStr = value
						state.isEditor = true;
					})

			};
			// 获取路径
			const savePath = async () => {
				if (state.overlay) {
					state.pathStr = state.overlay
						.getPath()
						.map((item) => {
							return item.lng + ',' + item.lat;
						})
						.join(',');
				}

				if (!state.pathStr) {
					ElMessage({
						message: '未绘制图形',
						type: 'warning',
					});
					return;
				}
				if (!state.form.areaName) {
					ElMessage({
						message: '请输入片区名称',
						type: 'warning',
					});
					return;
				}
				if (state.form.areaTypeCode === '') {
					ElMessage({
						message: '请选择片区类型',
						type: 'warning',
					});
					return;
				}
				if (state.form.nodeId === '') {
					ElMessage({
						message: '请选择片区',
						type: 'warning',
					});
					return;
				}
				state.form.coordinate = state.pathStr;
				if (state.graphicalCurrent === 0) {
					state.centerPoint = state.overlay.point;
					state.radius = state.map.getDistance(state.overlay.point, state.overlay.getPath()[0]);
					state.form.type = 'circle';
					state.form.circle = state.centerPoint.lng + ',' + state.centerPoint.lat;
					state.form.radius = state.radius;
				} else {
					state.form.type = 'polygon';
				}
				let quest = state.form.id ? updateArea : insertArea;
				const data = await quest(state.form);
				back();
				getList();
				ElMessage({
					message: '操作成功',
					type: 'success',
				});
			};
			const seePath = () => {
				state.pathObj[['circle', 'polygon', 'polygon'][state.graphicalCurrent]] =
					state.overlay.getPath();
				state.pathStr = state.overlay
					.getPath()
					.map((item) => {
						return item.lng + ',' + item.lat;
					})
					.join(',');
				console.log(state.overlay.getPath());
			};
			// 获取列表
			const getList = async () => {
				if (state?.typeCurrent?.length) {
					state.queryForm.areaTypeCode = state.typeCurrent.join(',');
				} else {
					state.queryForm.areaTypeCode = '';
				}
				if (state?.stateCurrent?.length) {
					state.queryForm.status = state.stateCurrent.join(',');
				} else {
					state.queryForm.status = '';
				}
				if (state.tableLoading) {
					return;
				}
				state.tableLoading = true;
				const data = await getSelectByParamsList(state.queryForm);
				console.log(data);
				state.tableLoading = false;
				state.tableData = data;
			};
			// 删除操作
			const delArea = (id) => {
				ElMessageBox.confirm('是否确认删除当前区域?', '警告', {
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						type: 'warning',
					})
					.then(async () => {
						const data = await deleteAreaById({
							id
						});
						back();
						getList();
						ElMessage({
							type: 'success',
							message: '操作成功',
						});
					})
					.catch(() => {});
			};
			onMounted(() => {
				getList();
			});
			// 页面离开
			onBeforeUnmount(() => {});
			return {
				...toRefs(state),
				typeClick,
				stateClick,
				editArea,
				operationClick,
				CircleDemo,
				handedit,
				Search,
				ArrowLeft,
				WarningFilled,
				savePath,
				back,
				seePath,
				getList,
				open,
				delArea,
			};
		},
	});
</script>
<style scoped lang="less">
	.rc-container {
		padding-top: 2vw;

		.operation-group {
			//   margin: 1.5625vw 0;
			display: flex;
			align-items: center;

			.operation-item {
				flex-grow: 1;
				text-align: center;
				position: relative;
				color: rgba(255, 255, 255, 0.3);
				padding: 1.125vw;
				cursor: pointer;
			}

			.operation-item.active {
				color: white;
			}

			.operation-item.active::after {
				position: absolute;
				content: '';
				width: 30px;
				height: 4px;
				background: #037bff;
				border-radius: 2px;
				bottom: 0.5vw;
				left: 50%;
				margin-left: -15px;
			}

			.operation-line {
				width: 1px;
				height: 18px;
				background: #ffffff;
				opacity: 0.3;
			}
		}

		.table-grop {
			width: 100%;
			border-top: 1px solid rgba(235, 235, 235, 0.2);
			margin-top: 1vw;
			max-height: 59vh;
			overflow-y: auto;

			.table-cell {
				border-bottom: 1px solid rgba(235, 235, 235, 0.2);
				padding: 0.8vw 0;
				display: block;

				.header {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.name {
						font-size: 1.0416vw;
						color: white;
					}

					.tip {
						color: rgba(250, 170, 111, 1);
					}

					.tip.blue {
						color: #4979ff;
					}
				}

				.con {
					display: flex;
					justify-content: space-between;
					padding: 0.3vw 0;

					.con-text {
						color: rgba(255, 255, 255, 1);
					}

					.con-right {
						display: flex;
						align-items: center;
					}
				}

				.select {
					display: flex;
					color: white;

					.bor {
						padding: 4px 10px;
						border: 1px solid rgba(3, 123, 255, 1);
						border-radius: 4px;
					}
				}
			}
		}

		.tag-group {
			display: flex;
			color: rgba(255, 255, 255, 0.7);
			align-items: center;
			margin: 0 0 1vw;

			.roadName {
				color: white;
				border: 1px solid rgba(3, 123, 255, 1);
				border-radius: 4px;
			}

			.tag-label {
				padding-right: 2.08vw;
			}

			.tag-cell {
				display: flex;
			}

			.tag-item {
				padding: 4px 10px;
				cursor: pointer;
				margin-right: 1.0416vw;
			}

			.tag-item.active {
				color: white;
				background: #037bff;
				border-radius: 4px;
			}

			.today {
				display: flex;
				justify-content: space-between;
				flex-grow: 1;

				.refresh {
					cursor: pointer;
					color: #4979ff;
				}
			}

			.date {
				border: 1px solid rgba(3, 123, 255, 1);
				border-radius: 4px;
			}
		}

		.search {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.search-input {
				border: 1px solid #037bff;
				border-radius: 8px;
				flex-grow: 3;
			}

			.export {
				flex-grow: 2;
				color: rgba(3, 123, 255, 1);
				display: flex;
				text-align: right;
				align-items: center;
				justify-content: flex-end;

				span {
					cursor: pointer;
				}
			}
		}

		.statistics-dio {
			position: absolute;
			left: calc(100% + 10px);
			height: 80vh;
			top: 0;
			width: 27.0833vw;
			background: rgba(0, 0, 0, 0.8);
			transform: translateX(-100vw);
			transition: all 0.5s;
			z-index: 9;
			display: flex;
			flex-direction: column;

			.head {
				text-align: center;
				color: white;
				font-size: 1.0416vw;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 1.0416vw;

				.back {
					left: 0.5vw;
					position: absolute;
					cursor: pointer;
					display: flex;
					align-items: center;
					font-size: 14px;
				}

				.save {
					right: 1vw;
					position: absolute;
					cursor: pointer;
					color: rgba(3, 123, 255, 1);
					font-size: 16px;
				}
			}

			.title {
				position: relative;
				padding-left: 1.25vw;
				color: white;
				display: flex;
				align-items: center;
			}

			.title::before {
				position: absolute;
				content: '';
				display: block;
				width: 2px;
				height: 12px;
				left: 0.875vw;
				background-color: rgba(3, 123, 255, 1);
			}

			.or-group {
				padding: 1vw 1vw 0;
				display: flex;
				align-items: center;
				color: rgba(255, 255, 255, 0.6);

				.val {
					border: 1px solid #666666;
					border-radius: 4px;
					flex-grow: 1;
					margin-left: 1vw;
				}
			}

			.selected {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 1vw 0;
				color: white;

				.or {
					display: flex;
					align-items: center;
				}
			}

			.table {
				padding: 0 1vw;
				border-top: 0 none;
				box-sizing: border-box;
			}

			.tools-group {
				display: flex;
				align-items: center;
				margin: 1vw;

				.tools-item {
					text-align: center;
					padding: 1vw 2vw;
					cursor: pointer;
					color: white;

					img {
						margin: 5px auto;
					}
				}

				.tools-item.active {
					background: rgba(3, 123, 255, 1);
				}
			}

			.select-cell {
				display: flex;
				width: 100%;
				padding: 0 0.5vw;
				box-sizing: border-box;

				.select-cell-item {
					margin: 0 0.5vw;
					flex-grow: 1;
					border: 1px solid rgba(3, 123, 255, 1);
					border-radius: 4px;
				}
			}
		}

		.edit {
			color: rgba(87, 162, 245, 1);
			cursor: pointer;
		}

		.del {
			color: rgba(250, 86, 86, 1);
			cursor: pointer;
		}

		.line {
			width: 1px;
			height: 10px;
			background-color: rgba(235, 235, 235, 0.4);
			margin: 0 1vw;
		}

		.statistics-dio.show {
			transform: translateX(0);
		}

		.add-road-tips {
			font-size: 1.0416vw;
			padding: 10px;
			background-color: #e2e2e2;
			color: #ee4c00;
		}

		.btn-group {
			display: flex;
			align-items: center;

			div {
				margin-right: 1vw;
			}
		}

		.show-title {
			color: white;
			margin: 1vw;
		}

		.show-json {
			border: 1px solid #666666;
			border-radius: 4px;
			margin: 0 1vw;
			padding: 1vw;
			height: 125px;
			overflow-y: scroll;
			color: white;
			word-break: break-all;
		}

		.btn-bottom {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 1vw;
		}
	}
</style>
<style>
	.el-tree {
		background: none;
	}

	.not-data {
		padding-top: 1vw;
		color: white;
	}
</style>